package com.itheima.Jiuye13;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@SuppressWarnings("all")
public class Test01 {
    public static void main(String[] args) {
        //创建两个锁对象, 都是Lock
        Lock lockA = new ReentrantLock();
        Lock lockB = new ReentrantLock();
        //创建两条线程对象, 且分别开启
        //将任务作为 Thread类构造方法的参数
        new Thread(()->{
            while (true){
                //判断, 能不能获取到A锁, 获取到就返回true  否则返回false
                if (lockA.tryLock()){
                    //继续判断, 能不能获取到 B锁
                    try {
                        //判断, 能不能获取到B锁, 获取到就返回true
                        if (lockB.tryLock()){
                            try {
                                System.out.println("先获取到A , 然后再获取到B...");
                            } finally {
                                lockB.unlock();
                            }
                        }

                    } finally {
                        lockA.unlock();
                    }
                }
            }
        }).start();



        new Thread(()->{
            while (true){
                //判断, 能不能获取到b锁, 获取到就返回true  否则返回false
                if (lockB.tryLock()){
                    try {
                        //判断, 能不能获取到A锁, 获取到就返回true
                        if (lockA.tryLock()){
                            try {
                                System.out.println("先获取到BBBB , 然后再获取到aaaa...");
                            } finally {
                                lockA.unlock();
                            }
                        }

                    } finally {
                        lockB.unlock();
                    }
                }
            }
        }).start();

    }
}
